/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package group2.filters;

import group2.core.entities.CamelUser;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author cnilsson
 */
public class LoginFilter implements javax.servlet.Filter {

    private final String strPost = "/group2_dat076-camelblog_war_1.0-SNAPSHOT/jsf/newPost.jsf";
    private final String strAdminCtrl = "/group2_dat076-camelblog_war_1.0-SNAPSHOT/jsf/adminCtrl.jsf";
    private final String strStart = "/group2_dat076-camelblog_war_1.0-SNAPSHOT/jsf/dunes.jsf";
    protected ServletContext servletContext;
    private CamelUser loggedInUser = null;

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(
            ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String str = req.getRequestURI();
        try {
            HttpSession httpSession = req.getSession();
            loggedInUser = (CamelUser) httpSession.getAttribute("username");
        } catch (Exception e) {
        }
        if (str.equals(strAdminCtrl)) {
            if (loggedInUser != null) {
                switch (loggedInUser.getUserLevel()) {
                    case USER:
                        break;
                    case WRITER:
                        break;
                    case ADMIN:
                        chain.doFilter(request, response);
                        break;
                }
            }
            resp.sendRedirect(strStart);
            chain.doFilter(request, resp);
        }
        chain.doFilter(request, resp);
    }

    /**
     * logic to accept or reject access to the page, check log in status
     * @return true when authentication is deemed valid
     */
    @Override
    public void destroy() {
        
    }
}
